import React, { useState, useEffect } from 'react';
import { IonCard, IonCardHeader, IonCardTitle, IonCardContent, IonButton, IonIcon, IonBadge } from '@ionic/react';
import { downloadOutline, checkmarkCircle, closeCircle } from 'ionicons/icons';
import { useTranslation } from 'react-i18next';
import { terminalService } from '../../services/TerminalService';

interface InstallationStep {
  command: string;
  description: string;
}

const OllamaInstallGuide: React.FC = () => {
  const { t } = useTranslation();
  const [isInstalled, setIsInstalled] = useState<boolean | null>(null);
  const [platform, setPlatform] = useState<'darwin' | 'linux' | 'win32'>('darwin');

  useEffect(() => {
    checkOllamaInstallation();
    detectPlatform();
  }, []);

  const checkOllamaInstallation = async () => {
    try {
      const result = await terminalService.executeCommand('ollama --version');
      setIsInstalled(result.exitCode === 0);
    } catch {
      setIsInstalled(false);
    }
  };

  const detectPlatform = async () => {
    try {
      const result = await terminalService.executeCommand('uname');
      if (result.output.toLowerCase().includes('darwin')) {
        setPlatform('darwin');
      } else if (result.output.toLowerCase().includes('linux')) {
        setPlatform('linux');
      } else {
        setPlatform('win32');
      }
    } catch {
      // Default to darwin if detection fails
      setPlatform('darwin');
    }
  };

  const getDownloadUrl = () => {
    switch (platform) {
      case 'darwin':
        return 'https://ollama.ai/download/Ollama-darwin.zip';
      case 'linux':
        return 'https://ollama.ai/download/ollama-linux-amd64';
      case 'win32':
        return 'https://ollama.ai/download/OllamaSetup.exe';
      default:
        return 'https://ollama.ai/download';
    }
  };

  const getInstallationSteps = (): InstallationStep[] => {
    switch (platform) {
      case 'darwin':
        return [
          {
            command: 'curl -fsSL https://ollama.ai/install.sh | sh',
            description: t('install.steps.darwin.curl')
          }
        ];
      case 'linux':
        return [
          {
            command: 'curl -fsSL https://ollama.ai/install.sh | sh',
            description: t('install.steps.linux.curl')
          }
        ];
      case 'win32':
        return [
          {
            command: '',
            description: t('install.steps.windows.download')
          }
        ];
      default:
        return [];
    }
  };

  const handleDownload = () => {
    window.open(getDownloadUrl(), '_blank');
  };

  const handleCopyCommand = (command: string) => {
    navigator.clipboard.writeText(command);
  };

  return (
    <IonCard className="mb-4">
      <IonCardHeader>
        <IonCardTitle className="flex items-center gap-2">
          {t('install.title')}
          {isInstalled !== null && (
            <IonBadge color={isInstalled ? 'success' : 'danger'}>
              <IonIcon icon={isInstalled ? checkmarkCircle : closeCircle} />
              {isInstalled ? t('install.status.installed') : t('install.status.notInstalled')}
            </IonBadge>
          )}
        </IonCardTitle>
      </IonCardHeader>
      <IonCardContent>
        <div className="space-y-4">
          {!isInstalled && (
            <>
              <p>{t('install.description')}</p>
              
              <div className="flex flex-col gap-2">
                <IonButton
                  expand="block"
                  onClick={handleDownload}
                  color="primary"
                >
                  <IonIcon slot="start" icon={downloadOutline} />
                  {t('install.download')}
                </IonButton>
              </div>

              <div className="mt-4">
                <h3 className="text-lg font-semibold mb-2">{t('install.instructions')}</h3>
                {getInstallationSteps().map((step, index) => (
                  <div key={index} className="mb-2">
                    <p className="text-sm mb-1">{step.description}</p>
                    {step.command && (
                      <div className="bg-base-200 p-2 rounded-lg flex justify-between items-center">
                        <code className="text-sm">{step.command}</code>
                        <IonButton
                          fill="clear"
                          size="small"
                          onClick={() => handleCopyCommand(step.command)}
                        >
                          {t('common.copy')}
                        </IonButton>
                      </div>
                    )}
                  </div>
                ))}
              </div>

              <div className="mt-4 text-sm">
                <p>{t('install.help.description')}</p>
                <a
                  href="https://github.com/ollama/ollama"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-primary hover:underline"
                >
                  {t('install.help.github')}
                </a>
              </div>
            </>
          )}
        </div>
      </IonCardContent>
    </IonCard>
  );
};

export default OllamaInstallGuide; 